﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using AutoMapper;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TyNetCoreBlog.Helpers;
using TyNetCoreBlog.Models.Dto.Blog;
using TyNetCoreBlog.Models.Dto.Category;
using TyNetCoreBlog.Repository.RepositoryWrapper;
using static TyNetCoreBlog.Helpers.ResponseMsg;

namespace TyNetCoreBlog.Controllers
{
    [Route("api/categories")]
    [EnableCors("any")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        private readonly IRepositoryWrapper _repositoryWrapper;
        private readonly IMapper _mapper;

        public CategoryController(IRepositoryWrapper repositoryWrapper,IMapper mapper)
        {
            this._repositoryWrapper = repositoryWrapper ?? throw new ArgumentNullException(nameof(repositoryWrapper));
            this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 获取所有分类（博客数量倒序）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<IEnumerable<CategoryDto>>> GetCategories()
        {
            var cates = (await _repositoryWrapper.Category.GetAllAsync())
                .OrderByDescending(x => x.Blogs.Count);
            var cateDtoList = _mapper.Map<IEnumerable<CategoryDto>>(cates).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, cateDtoList));
        }

        
        /// <summary>
        /// 通过ID获取一个分类
        /// </summary>
        /// <param name="cateId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{cateId}", Name = nameof(GetOneCategory))]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<CategoryDto>> GetOneCategory(int cateId)
        {
            var cate = await _repositoryWrapper.Category.GetByIdAsync(cateId);
            if (cate == null)
            {
                return NotFound(new ResponseMsg(ApiStatus.NotFound));
            }
            var cateDtoList = _mapper.Map<CategoryDto>(cate);
            return Ok(new ResponseMsg(ApiStatus.OK, cateDtoList));
        }


        /// <summary>
        /// 获取分类下所有博客
        /// </summary>
        /// <param name="cateId">分类ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{cateId}/blogs")]
        [ResponseCache(Duration = 3)]
        public async Task<ActionResult<IEnumerable<BlogDto>>> GetBlogsByCateId(int cateId)
        {
            var blogs = await _repositoryWrapper.Blog.GetByConditionAsync(x => x.CategoryId == cateId);
            var blogDtoList = _mapper.Map<IEnumerable<BlogDto>>(blogs).ToList();
            return Ok(new ResponseMsg(ApiStatus.OK, blogDtoList));
        }


    }
}
